using UnityEngine;

public class BulletController : MonoBehaviour
{
    [Header("弹幕设置")]
    public float speed = 15f;
    public float lifetime = 5f;
    public int damage = 1;
    
    [Header("弹幕类型")]
    public BulletType bulletType = BulletType.Player;
    
    [Header("视觉效果")]
    public bool hasTrail = true;
    public Color bulletColor = Color.white;
    
    private Rigidbody2D rb;
    private Vector2 direction;
    private float timer;
    
    // 对象池相关
    private BulletSpawner bulletSpawner;
    
    public enum BulletType
    {
        Player,
        Enemy
    }
    
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        
        if (rb == null)
        {
            rb = gameObject.AddComponent<Rigidbody2D>();
        }
        
        // 设置刚体属性
        rb.gravityScale = 0f;
        rb.freezeRotation = true;
        
        // 设置默认方向
        if (direction == Vector2.zero)
        {
            direction = bulletType == BulletType.Player ? Vector2.up : Vector2.down;
        }
        
        // 设置初始速度
        rb.velocity = direction * speed;
        
        // 设置视觉效果
        SetupVisualEffects();
        
        Debug.Log($"弹幕已创建: 类型={bulletType}, 速度={speed}, 方向={direction}");
    }
    
    void Update()
    {
        // 生命周期管理
        timer += Time.deltaTime;
        if (timer >= lifetime)
        {
            DestroyBullet();
            return;
        }
        
        // 边界检查
        if (BoundaryManager.Instance != null && BoundaryManager.Instance.IsOutOfBounds(transform.position))
        {
            DestroyBullet();
        }
    }
    
    void SetupVisualEffects()
    {
        // 设置子弹颜色
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();
        if (spriteRenderer != null)
        {
            spriteRenderer.color = bulletColor;
        }
        
        // 添加拖尾效果
        if (hasTrail)
        {
            TrailRenderer trail = GetComponent<TrailRenderer>();
            if (trail == null)
            {
                trail = gameObject.AddComponent<TrailRenderer>();
            }
            
            trail.time = 0.2f;
            trail.startWidth = 0.1f;
            trail.endWidth = 0.02f;
            trail.material = new Material(Shader.Find("Sprites/Default"));
            trail.startColor = new Color(bulletColor.r, bulletColor.g, bulletColor.b, 0.8f);
            trail.endColor = new Color(bulletColor.r, bulletColor.g, bulletColor.b, 0.1f);
        }
    }
    
    void OnTriggerEnter2D(Collider2D other)
    {
        HandleCollision(other);
    }
    
    void HandleCollision(Collider2D other)
    {
        if (bulletType == BulletType.Player)
        {
            // 玩家子弹碰撞敌人
            if (other.CompareTag("Enemy"))
            {
                EnemyController enemy = other.GetComponent<EnemyController>();
                if (enemy != null)
                {
                    enemy.TakeDamage(damage);
                }
                
                CreateHitEffect();
                DestroyBullet();
            }
            // 玩家子弹碰撞宝箱
            else if (other.CompareTag("TreasureChest"))
            {
                TreasureChestController treasureChest = other.GetComponent<TreasureChestController>();
                if (treasureChest != null)
                {
                    treasureChest.TakeDamage(damage);
                }
                
                CreateHitEffect();
                DestroyBullet();
            }
        }
        else if (bulletType == BulletType.Enemy)
        {
            // 敌人子弹碰撞玩家
            if (other.CompareTag("Player"))
            {
                PlayerController player = other.GetComponent<PlayerController>();
                // 这里可以添加玩家受伤逻辑
                
                CreateHitEffect();
                DestroyBullet();
            }
        }
    }
    
    void CreateHitEffect()
    {
        // 创建击中特效
        GameObject hitEffect = new GameObject("HitEffect");
        hitEffect.transform.position = transform.position;
        
        // 添加粒子效果（简单版本）
        ParticleSystem particles = hitEffect.AddComponent<ParticleSystem>();
        var main = particles.main;
        main.startLifetime = 0.5f;
        main.startSpeed = 5f;
        main.startSize = 0.1f;
        main.startColor = bulletColor;
        main.maxParticles = 10;
        
        var emission = particles.emission;
        emission.rateOverTime = 0;
        emission.SetBursts(new ParticleSystem.Burst[]
        {
            new ParticleSystem.Burst(0.0f, 10)
        });
        
        // 自动销毁特效
        Destroy(hitEffect, 1f);
    }
    
    public void SetDirection(Vector2 newDirection)
    {
        direction = newDirection.normalized;
        if (rb != null)
        {
            rb.velocity = direction * speed;
        }
    }
    
    public void SetSpeed(float newSpeed)
    {
        speed = newSpeed;
        if (rb != null)
        {
            rb.velocity = direction * speed;
        }
    }
    
    public void SetBulletType(BulletType type)
    {
        bulletType = type;
        
        // 根据类型设置不同的颜色
        switch (type)
        {
            case BulletType.Player:
                bulletColor = Color.cyan;
                break;
            case BulletType.Enemy:
                bulletColor = Color.red;
                break;
        }
        
        SetupVisualEffects();
    }
    
    public void DestroyBullet()
    {
        Debug.Log($"弹幕已销毁: {gameObject.name}");
        
        if (bulletSpawner != null)
        {
            bulletSpawner.ReturnBulletToPool(gameObject);
        }
        else
        {
            Destroy(gameObject);
        }
    }
    
    public void SetBulletSpawner(BulletSpawner spawner)
    {
        bulletSpawner = spawner;
    }
    
    void OnDrawGizmos()
    {
        // 绘制弹幕方向
        Gizmos.color = bulletColor;
        Gizmos.DrawLine(transform.position, transform.position + (Vector3)direction * 2f);
        
        // 绘制弹幕范围
        Gizmos.DrawWireSphere(transform.position, 0.2f);
    }
}